/*
 * @(#)DmsNewFolder.java
 *
 * Copyright (c) 2003 DCIVision Ltd
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of DCIVision
 * Ltd ("Confidential Information").  You shall not disclose such Confidential
 * Information and shall use it only in accordance with the terms of the license
 * agreement you entered into with DCIVision Ltd.
 */
package com.dcivision.workflow.action;

import java.sql.Connection;
import java.util.List;

import org.quartz.JobDataMap;

import com.dcivision.dms.bean.DmsDocument;
import com.dcivision.dms.bean.DmsDocumentDetail;
import com.dcivision.dms.core.DocumentOperationManager;
import com.dcivision.dms.core.DocumentRetrievalManager;
import com.dcivision.dms.dao.DmsDocumentDAObject;
import com.dcivision.framework.ApplicationException;
import com.dcivision.framework.DataSourceFactory;
import com.dcivision.framework.ErrorConstant;
import com.dcivision.framework.EventLogger;
import com.dcivision.framework.GlobalConstant;
import com.dcivision.framework.SessionContainer;
import com.dcivision.framework.SystemFunctionConstant;
import com.dcivision.framework.Utility;
import com.dcivision.framework.bean.AbstractBaseObject;
import com.dcivision.workflow.WorkflowErrorConstant;
import com.dcivision.workflow.bean.WorkflowProgress;
import com.dcivision.workflow.core.WorkflowProcessor;

/**
 *  DmsNewFolder.java
 *
 *  This class is the automatic task handler for publish public document.
 *
 *  @author      Angus Shiu
 *  @company     DCIVision Limited
 *  @creation date   26/01/2003
 *  @version     $Revision: 1.10.2.1 $
 */
public class DmsNewFolder extends com.dcivision.workflow.core.WorkflowProcessor {

  public static final String REVISION = "$Revision: 1.10.2.1 $";

  private static Integer nDetailID = new Integer(39); //hard code for demo.

  public DmsNewFolder() {
    this.numOfRoutine = 1;
    this.labelType = WorkflowProcessor.LABEL_TYPE_USER_DEFINE;
    this.labelString = new String[] {"workflow.label.step_status_G"};
  }

  public synchronized void execute(JobDataMap dataMap, WorkflowProgress currentProgress) throws ApplicationException {
    log.info("***** DmsNewFolder workflow processor BEGIN *****");
    Connection conn = null;

    Integer trigerEventUserID = new Integer(0);
    String serverName = "127.0.0.1";
    String functionName = SystemFunctionConstant.WORKFLOW_TASK;
    String errorMessage = "";

    try {
      //* get the DB Connection
      SessionContainer sessionCon = this.getSessionContainer();

      /*************************************************************
       *  get Event Log Information Begin
       *************************************************************/
      if (!Utility.isEmpty(sessionCon.getUserRecordID())) {
        trigerEventUserID = sessionCon.getUserRecordID();
      }

      if (!Utility.isEmpty(sessionCon.getUserIPAddress())) {
        serverName = sessionCon.getUserIPAddress();
      }
      errorMessage =  "DmsNewFolder.java -- Track ID: " + currentProgress.getTrackID() +
                      ", Workflow Progress ID : " + currentProgress.getID() +
                      ", Workflow Step ID: " + currentProgress.getWorkflowStepID() +
                      "<br> ";
      /*************************************************************
       *  get Event Log Information End
       *************************************************************/
      //for schedule job useing the processer connection.
      isLocalConnection = false;
      if(!Utility.isEmpty(this.getConnection())){
        conn = this.getConnection();
      }else{
        isLocalConnection = true;
        conn = DataSourceFactory.getConnection();
      }

      //* get relevant information from
      AbstractBaseObject workflowObject = (AbstractBaseObject) dataMap.get("WORKFLOW_OBJECT");
      log.debug("workflow object class name: "+workflowObject.getClass().getName());
      Integer docID = workflowObject.getID();

      //* create required DAObject
      DmsDocumentDAObject docDAO = new DmsDocumentDAObject(sessionCon, conn);
      DmsDocument oldDoc = (DmsDocument) docDAO.getObjectByID(docID);

      DocumentRetrievalManager retrievalManager = new DocumentRetrievalManager(sessionCon, conn);
      DocumentOperationManager operationManager = new DocumentOperationManager(sessionCon, conn);
      List detailList = retrievalManager.getDocumentDetailList(docID);
      String folderName = null;
      DmsDocumentDetail detail = null;
      if (detailList!=null && detailList.size() > 0) {
        for (int i=0; i<detailList.size(); i++) {
          detail  = (DmsDocumentDetail)detailList.get(i);
          if (nDetailID.equals(detail.getUserDefinedFieldDetailID())) {
           folderName = detail.getFieldValue();
           break;
          }
          if (folderName!=null) {
            List docList = retrievalManager.getFolderTreeByParentIDRootID(oldDoc.getParentID(), oldDoc.getRootID());

            DmsDocument newFolderDocuemnt = null;
            if (docList != null && docList.size() > 0) {
              Integer tmpID = null;
              for (int j=0; j<docList.size();j++) {
                DmsDocument tmpFolder = (DmsDocument) docList.get(j);
                if (GlobalConstant.RECORD_STATUS_ACTIVE.equals(tmpFolder.getRecordStatus()) && folderName.equals(tmpFolder.getDocumentName())) {
                  tmpID = tmpFolder.getID();
                }
              }
              oldDoc.setParentID(tmpID); //get first element
            }
            else {
              DmsDocument doc = new DmsDocument();
              doc.setRootID(oldDoc.getRootID());
              doc.setParentID(oldDoc.getParentID());
              doc.setDocumentName(folderName);
              doc.setDocumentType(DmsDocument.FOLDER_TYPE);
              // Create Folder According to the User Defined Field.
              newFolderDocuemnt = operationManager.createFolder(doc);
              oldDoc.setParentID(newFolderDocuemnt.getID());

            }
            operationManager.updateDocument(oldDoc); //not update item
          }
        }
      }

      //* after the execution, set the desired appropriate out number
      this.returnRoutineIndex = 1; //* should be between 0 and numOfRoutine-1
      //* if need to auto-Execute the following step, set the below variable to true (default false)
      this.bAutoExecuteNextStep=false; this.bCreateNextWorkflowProgress=true;

      if(isLocalConnection){
        conn.commit();
      }
    } catch (ApplicationException appEx) {
      log.error("Application exception:\n"+appEx);
      /***********************************
       *  Record the Event Log.
       ***********************************/
      EventLogger.logEventMessage(trigerEventUserID, serverName, errorMessage, appEx.getMsgCode(), WorkflowErrorConstant.LOG_AUTO_TASK_ERROR_CODE, functionName, appEx.toString() );

      throw appEx; //* prop
    } catch (Exception e) {
      log.error("Error during processing this automatic task.", e);
      /***********************************
       *  Record the Event Log.
       ***********************************/
      EventLogger.logEventMessage(trigerEventUserID, serverName, errorMessage, ErrorConstant.COMMON_FATAL_ERROR, WorkflowErrorConstant.LOG_AUTO_TASK_ERROR_CODE, functionName, e.toString() );

      throw new ApplicationException(ErrorConstant.COMMON_FATAL_ERROR); //* throw an applicationExcpetion with an appropriate
    } finally {
      if(isLocalConnection){
        try { conn.close(); } catch (Exception ignore) {} finally { conn = null; }
      }
    }

    log.info("***** DmsNewFolder workflow processor END   *****");
  }

}
